﻿using FB.Mvc.Controllers;
using FB.Providers;
using FB.Providers.EmployeeInfo;
using FCDB.Entity;
using FCDB.Repository;
using FCDB.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Wf5.Engine.Business;
using Wf5.Engine.Common;

namespace FCDB.Web.Controllers
{
    public abstract class FormBaseController : BaseController
    {
        protected FB.Services.MailService _mailService=new FB.Services.MailService(new FCDB.Web.Helpers.FCDBSmtpClientProxy());
        protected EmployeeInfoUnit _EMPInfoUnit=EmployeeInfoManager.GetEmployeeInfoUnit();
        protected EmployeeInfoService _EMPInfoSvr=EmployeeInfoManager.GetEmployeeInfoService();
        protected IWorkflowService _wfService = new WorkflowService();
        protected FormRepository _formRepository = new FormRepository(); 
        private WfActivityInstanceRepository _wfActivityInstanceRespository = new WfActivityInstanceRepository();
        /// <summary>
        /// 保存页面寄存ViewBase
        /// </summary>
        /// <param name="formId">表单的ID</param>
        /// <param name="AppInstanceID">流程的ID</param>
        protected void SaveCommonViewBase(long formId, long AppInstanceID, string FormType=null)
        {
           

            String ProcessGuid = Request["ProcessGuid"];
            if(string.IsNullOrEmpty(FormType)) 
              FormType = (string)RouteData.Values["action"];
            ViewBag.FormAttachments = _formRepository.GetFormAttachments(FormType, formId);
            if (AppInstanceID == 0)
            {
                ViewBag.FormsRelations = _formRepository.GetFormsRelationsByForm(formId, FormType);
                ViewBag.FormCirculatedDocumentLogs = new List<FCDB.Entity.FormCirculatedDocumentLog>();
            }
            else
            {
                ViewBag.FormsRelations = _formRepository.GetFormsRelationsByProcess(new Guid(ProcessGuid), AppInstanceID);
                ViewBag.FormCirculatedDocumentLogs = _formRepository.GetDocumentLogs(new Guid(ProcessGuid), AppInstanceID);
            }
            ViewBag.FormUserID = this.UserID;

        }


         
        /// <summary>
        /// 获取流程审批节点和审批纪录
        /// </summary>
        /// <returns>返回流程节点</returns>
        protected IList<ActivityEntity> GetProcessActivitiesCheckLog()
        {
            String ProcessGuid = Request["ProcessGuid"];
            long AppInstanceID = 0;
            long.TryParse(Request["AppInstanceID"], out AppInstanceID);
            WfProcessInstance ProcessInstance = null;
            IList<FormCheckLog> checkLogs = null;
            ProcessModel processModel = new ProcessModel(new Guid(ProcessGuid));
            List<ActivityEntity> activitryList = new List<ActivityEntity>();
            IList<WfActivityInstance> appinstanceActivityList = null;
            IList<ActivityEntityModel> activityEntityModelList = new List<ActivityEntityModel>();
            if (AppInstanceID != 0)
            {
                ProcessInstance = _formRepository.Get<WfProcessInstance>(AppInstanceID);
                checkLogs = _formRepository.GetFormCheckLogs(AppInstanceID);
                appinstanceActivityList = _wfActivityInstanceRespository.GetProcessActivityList(AppInstanceID, new Guid(ProcessGuid));
            }
            Dictionary<string,string> conditionKeyPair=null;
            ActivityEntity activity = processModel.GetFirstActivity();
            IList<ActivityEntity> currentActivityList = new List<ActivityEntity>();
            NextActivityMatchedResult nextActivityResult = processModel.GetNextActivityList(activity, conditionKeyPair);
            foreach (var item in nextActivityResult.Root)
            {
                if (item.Transition.Condition != null && item.Transition.Condition.ConditionText.Trim() == "CheckState==2")
                {
                    continue;
                }
                currentActivityList.Add(item.Activity);
            }
            while (currentActivityList.Count > 0)
            {
                activity = currentActivityList[0];
                currentActivityList.Remove(activity);
                if (activitryList.Count(t => t.ActivityGUID == activity.ActivityGUID) > 0)
                {
                    continue;
                }
                if (activitryList.Count(t => t.ActivityGUID == activity.ActivityGUID) == 0 && activity.NodeType != NodeTypeEnum.EndNode && activity.NodeType != NodeTypeEnum.GatewayNode)
                { 
                    activitryList.Add(activity);
                    if (ProcessInstance != null)
                    {
                        #region 添加审批节点纪录
                        //添加审批节点纪录
                        ActivityEntityModel model = new ActivityEntityModel(activity);
                        if (appinstanceActivityList.Count(t => t.ActivityGUID == activity.ActivityGUID) == 0)
                        {
                            model.NodeState = null;
                        }
                        else
                        {
                            WfActivityInstance instance = appinstanceActivityList.First(t => t.ActivityGUID == activity.ActivityGUID);
                            IList<FormCheckLog> logList = checkLogs.Where(t => t.ActivityInstanceGuid == activity.ActivityGUID).ToList();
                            FormCheckLog log = checkLogs.FirstOrDefault(t => t.ActivityInstanceGuid == activity.ActivityGUID);
                            model.NodeState = (NodeStateEnum)instance.State;
                            if (log != null)
                            {
                                model.CheckContent = log.CheckContent;
                                model.CheckState = (short)log.CheckState;
                                model.CheckUserID = log.CheckUserID;
                                model.CheckUserName = log.CheckUserName;
                                model.CheckUserID = log.CheckUserID;
                                model.CheckUserName = log.CheckUserName;
                                model.CheckTime = log.CheckTime;
                                model.CreateTime = log.CreateTime;
                                model.SendUserID = log.SendUserID;
                                model.SendUserName = log.SendUserName;
                                model.FormCheckLogList = logList;
                            }
                            else
                            {
                                model.CheckUserID = instance.EndedByUserID;
                                model.CheckUserName = instance.EndedByUserName;
                                model.CreateTime = instance.CreatedDateTime;
                                model.SendUserID = instance.CreatedByUserID;
                                model.SendUserName = instance.CreatedByUserName;
                            }
                            model.FromDiv = activity.FromDiv;
                        }
                        activityEntityModelList.Add(model);
                        #endregion
                    }
                } 
                nextActivityResult = processModel.GetNextActivityList(activity, conditionKeyPair);
                foreach (var item in nextActivityResult.Root)
                {
                    if (currentActivityList.Count(t => t.ActivityGUID == item.Activity.ActivityGUID) == 0)
                    {
                        if (item.Transition.Condition != null &&( item.Transition.Condition.ConditionText.Trim() == "CheckState==2" || item.Transition.Condition.ConditionText.Trim().IndexOf("CheckState==2")>-1))
                        {
                            continue; 
                        }
                        else
                        {
                            currentActivityList.Add(item.Activity);
                        }
                    } 
                }
            }
           activitryList= activitryList.OrderBy(t => t.Index).ToList();
            ViewBag.ActivitryEntityList = activitryList;
            if (ProcessInstance != null)
            {
                activityEntityModelList= activityEntityModelList.OrderBy(t => t.Index).ToList();
                ViewBag.ActivityCheckLogs = activityEntityModelList;
            }
            
            return activitryList;
        } 






    }
}
